package com.tenwives.ashop.kernel;

import lombok.Data;
import lombok.ToString;

import java.util.List;
import java.util.UUID;

@ToString
@Data
public class Trade {
    String id;
    Shop shop;
    Customer customer;
    List<Coupon> couponList;
    List<Special> specialList;
    List<Goods> goodsList;
    double totalPrice;
    double actualPrice;

    private Trade() {
        this.id = UUID.randomUUID().toString();
    }

    public Trade(Shop shop, Customer customer, List<Coupon> couponList, List<Special> specialList, List<Goods> goodsList) {
        this();
        this.shop = shop;
        this.customer = customer;
        this.couponList = couponList;
        this.specialList = specialList;
        this.goodsList = goodsList;
        this.calculateTotalPrice();
        this.calculateActualPrice();
    }

    private void calculateActualPrice() {
        double total = goodsList.stream().mapToDouble(this::priceOf).sum();
        this.actualPrice = couponList.stream().mapToDouble(coupon -> coupon.apply(total)).min().orElse(total);
    }

    private void calculateTotalPrice() {
        this.totalPrice = goodsList.stream().mapToDouble(Goods::getTotal).sum();
    }

    private double priceOf(Goods goods) {
        return specialList.stream().filter(special -> special.test(goods)).mapToDouble(special -> special.apply(goods)).findFirst().orElse(goods.getTotal());
    }

}
